package com.utsirc.activities;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.utsirc.R;
import com.utsirc.UTSirC;
import com.utsirc.types.ChatMessage;

public class ChatFragment extends Fragment implements OnClickListener,
		OnEditorActionListener {

	public static ChatFragment instance;

	ChatAdapter chatAdapter;

	/**
	 * temporary chat history since we're re-using the same activity for
	 * different channels create a copy of the messages to be displayed
	 */
	List<ChatMessage> currentHistory;

	/**
	 * updates chat history with current channel name
	 */
	public void refresh() {

		String channelName = UTSirC.instance.currentChannel.channelName;
		currentHistory.clear();
		currentHistory.addAll(UTSirC.instance.messageHistoryGroup
				.get(channelName));
		this.chatAdapter.notifyDataSetChanged();
	}

	/**
	 * abstracted these logic out for both Send button and Enter key to work
	 */
	public void sendMessageAndClear() {
		EditText messageField = (EditText) getActivity().findViewById(
				R.id.message_field);
		String messageString = messageField.getText().toString();

		if (messageString.length() > 0) {
			UTSirC.instance.sendMessage(messageString);
			messageField.setText("");
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {

		instance = this;
		super.onCreate(savedInstanceState);
		this.currentHistory = new ArrayList<ChatMessage>();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View inflateView = inflater.inflate(R.layout.chat, container, false);
		inflateView.setBackgroundResource(R.drawable.frag_background);

		EditText textField = (EditText) inflateView
				.findViewById(R.id.message_field);
		textField.setOnEditorActionListener(this);

		Button sendButton = (Button) inflateView.findViewById(R.id.send_button);
		sendButton.setOnClickListener(this);

		ListView messageList = (ListView) inflateView
				.findViewById(R.id.messages);
		this.chatAdapter = new ChatAdapter(inflateView.getContext(),
				R.layout.message_layout, this.currentHistory);
		messageList.setAdapter(this.chatAdapter);

		// populating chat data
		this.refresh();

		return inflateView;
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.send_button) {
			this.sendMessageAndClear();
		}
	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

		if (v.getId() == R.id.message_field) {
			if (event != null && event.getAction() == KeyEvent.ACTION_DOWN) {
				if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
					this.sendMessageAndClear();
					return true;
				}
			}
		}
		return false;
	}
}

class ChatAdapter extends ArrayAdapter<ChatMessage> {

	private List<ChatMessage> chatMessages;
	private Context chatContext;
	private int textViewResourceId;

	public ChatAdapter(Context context, int textViewResourceId,
			List<ChatMessage> objects) {

		super(context, textViewResourceId, objects);
		this.chatContext = context;
		this.chatMessages = (List<ChatMessage>) objects;
		this.textViewResourceId = textViewResourceId;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		View v = convertView;

		if (v == null) {
			LayoutInflater vi = (LayoutInflater) chatContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(textViewResourceId, null);
		}

		ChatMessage chatMessage = chatMessages.get(position);
		TextView nickField = (TextView) v.findViewById(R.id.nick_field);
		TextView messageField = (TextView) v.findViewById(R.id.message_field);

		nickField.setText(chatMessage.sender);
		messageField.setText(chatMessage.message);

		return v;
	}
}